#pragma once
#include <iostream>
#include <pthread.h>
#include <string.h>

namespace MutexModule
{
    class Mutex
    {
    public:
        Mutex()
        {
            pthread_mutex_init(&_mutex, nullptr);
        }
        void Lock()
        {
            int n = pthread_mutex_lock(&_mutex);
            if (n == 0)
            {
                std::cout << "加锁成功" << std::endl;
            }
            else
            {
                std::cout << "加锁失败" << strerror(n) << std::endl;
            }
        }
        void UnLock()
        {
            int n = pthread_mutex_unlock(&_mutex);
            if (n == 0)
            {
                std::cout << "解锁成功" << std::endl;
            }
            else
            {
                std::cout << "解锁失败" << strerror(n) << std::endl;
            }
        }
        ~Mutex()
        {
            pthread_mutex_destroy(&_mutex);
        }

    private:
        pthread_mutex_t _mutex;
    };

    class LockGuard
    {
        public:
        LockGuard(Mutex &mutex):_mutex(mutex)
        {
            _mutex.Lock();
        }
        ~LockGuard()
        {
            _mutex.UnLock();
        }
        private:
        Mutex &_mutex;
    };
}